/**
 * 应用管理
 */
({
	launch : function() {
		var me = this;
		var perms = this.perms;
		var app = {
			browse:function() {
				var _this = this;
				var datagrid = $("<table></table>");
				var tools = $('<div></div>');
				if(perms.init) {
					var button = $("<a href='#' class='icon-add'></a>").appendTo(tools);
					button.click(function() {
						$.messager.mask().text("操作执行中，请稍后……");
						$.post(me.ctx + "/manager/app/init", {}, function(json) {
							datagrid.datagrid("options").pageNumber = 1;
							datagrid.datagrid("reload");
							$.messager.alert('提示：','初始化成功！\n共加载' + json.count + '个应用！', "info");
							$.messager.mask("close")
						}, "json");
						return false;
					});
				}
				var win = me.createWindow('<div></div>', {
					title:"应用管理",
					tools : tools,
					width:830,
					height:400
				});
				var columns = [
				        {field : 'id', title : '应用编号', width : 120},
				        {field : 'name', title : '应用名称', width : 120},
				        {field : 'icon', title:'图标', width:50, align:'center', formatter:function(value, row, index) {
				        	if(value) {
				        		return "<img src='" + me.ctx + value + "' width='30'/>";
				        	} else {
				        		return "";
				        	}
				        }},
				        {field : 'uri', title : '应用路径', width:400}
				];
				if(perms.permission) {
					columns.push({
						field:'permission', title:"权限分配", align:'center', formatter: function(value, row, index){
				        	return '<a class="l-btn l-btn-small l-btn-plain"><span class="l-btn-left l-btn-icon-left"><span class="l-btn-text l-btn-empty">&nbsp;</span><span class="l-btn-icon icon-permissions">&nbsp;</span></span></a>';
					}});
				}
				datagrid.appendTo(win);
				datagrid.datagrid({
					fit : true,
					url : me.ctx + "/manager/app/browse",
					pagination : true,
					rownumbers:true,
					pageSize : 10,
					selectOnCheck : false,
					checkOnSelect : false,
					singleSelect : true,
				    columns : [columns],
				    onClickCell : function(index, field, value) {
				    	if(field === "permission") {
				    		var rows = datagrid.datagrid("getRows");
				    		permission.browse(rows[index]);
				    	}
				    }
				});
				
				return win;
			}
		}
		
		var permission = {
			
			browse:function(app) {
				var _this = this;
				var datagrid = $("<table></table>");
				var tools = $('<div></div>');
				var addButton = $('<a href="#" class="icon-add"></a>').appendTo(tools);
				addButton.click(function() {
					_this.add(datagrid, app);
					return false;
				});
				var rmButton = $('<a href="#" class="icon-remove"></a>').appendTo(tools);
				rmButton.click(function() {
					$.messager.confirm("请确认：", "确认要删除所选权限吗？", function(isOk) {
						if(isOk) {
							var items = datagrid.datagrid("getChecked");
							var ids = [];
							$(items).each(function() {
								ids.push(this.id);
							});
							$.messager.mask().text("操作执行中，请稍后……");
							$.post(me.ctx + "/manager/permission/remove", {ids : ids}, function(data) {
								if(data.success) {
									rmButton.hide();
									datagrid.datagrid("reload");
								}
								$.messager.mask('close');
							}, "json");							
						}
					});
					return false;
				});
				var win = me.createWindow('<div></div>', {
					title:"权限管理 - <font color='blue'>所属应用：</font><font style='font-weight:normal;'>" + app.name + "</font>",
					width:550,
					height:300,
					tools : tools,
					minimizable:false,
					modal:true
				});
				var columns = [
				    	{field : 'checkbox', checkbox : true},
				        {field : 'id', title : '权限编号', width : 120},
				        {field : 'alias', title : '别名（用于js权限校验）', width : 200},
				        {field : 'name', title : '权限名称', width : 120}
				        
				   ];
				if(perms.source) {
					columns.push({
						field : 'source', title : '资源分配', align:'center', formatter: function(value, row, index){
				        	return '<a class="l-btn l-btn-small l-btn-plain"><span class="l-btn-left l-btn-icon-left"><span class="l-btn-text l-btn-empty">&nbsp;</span><span class="l-btn-icon icon-permissions">&nbsp;</span></span></a>';
					}});
				}
				datagrid.appendTo(win);
				datagrid.datagrid({
					fit : true,
					url : me.ctx + "/manager/permission/browse",
					queryParams : {
						app_id : app.id
					},
					pagination : true,
					pageSize : 10,
					selectOnCheck : false,
					checkOnSelect : false,
					singleSelect : true,
				    columns : [columns],
				    onClickCell : function(index, field, value) {
				    	if(field === "source") {
				    		var rows = datagrid.datagrid("getRows");
				    		source.browse(rows[index]);
				    	}
				    },
				    onCheckAll : function(rows) {
				    	if(rows.length > 0) {
				    		rmButton.show();
				    	}
				    },
				    onUncheckAll : function(rows) {
				    	rmButton.hide();
				    },
				    onCheck : function(index, row) {
				    	rmButton.show();
				    },
				    onUncheck : function(index, row) {
				    	if($(this).datagrid("getChecked").length < 1) {
				    		rmButton.hide();
				    	}
				    }, 
				    onLoadSuccess : function() {
				    	rmButton.hide();
				    }
				});
				return win;
			},
			
			add:function(datagrid, app) {
				var _this = this;
				var footer = $('<div style="padding:5px;text-align:right;"></div>');
				var win = me.createWindow('<div></div>', {
					title:"权限添加",
					width:300,
					height:160,
					resizable:false,
					minimizable:false,
					maximizable:false,
					modal:true,
					footer:footer
				});
				var form = $('<form style="width:100%;" method="post"></form>').appendTo(win);
				form.form({
					url : me.ctx + "/manager/permission/add",
					success: function(data){
						$.messager.mask("close");
				        var data = eval('(' + data + ')');
				        if (data.success){
				        	datagrid.datagrid("options").pageNumber = 1;
				            datagrid.datagrid("reload");
				            win.window("close");
				        } else {
				        	$.messager.alert('提示：', data.message, "info");
				        }
				    }
				});
				var table = $('<table width="100%" class="form-table"></table>').appendTo($('<div style="padding:5px 5px;"></div>').appendTo(form));
				var row = table.row();
				row.cell("别名：", {width:"60px"});
				var fieldContainer = row.cell($('<input type="hidden" name="app_id" value="' + app.id + '" />'));
				var field = $('<input type="text" name="alias" />').appendTo(fieldContainer);
				field.textbox({
					required: true,
					validType : ['letters', 'maxlength[20]']
				});
				
				row = table.row();
				row.cell("权限名称：");
				field = $('<input type="text" name="name" />');
				row.cell(field);
				field.textbox({
					required: true,
					validType : ['maxlength[50]']
				});
				row = table.row();
				row.cell("排序：");
				field = $('<input type="text" name="index" value="' + (datagrid.datagrid("getData").total + 1) + '" />');
				row.cell(field);
				field.numberbox({
					min:1,
					precision:0,
					required: true
				});
				var saveButton = $('<a href="#">提交</a>').appendTo(footer);
				saveButton.linkbutton({
					iconCls : 'icon-ok',
					onClick : function() {
						if(form.form("validate")) {
							$.messager.mask().text("操作执行中，请稍后……");
							form.form("submit");
						}
						return false;						
					}
				});
				footer.append("&nbsp;");
				var cancelButton = $('<a href="#">取消</a>').appendTo(footer);
				cancelButton.linkbutton({
					iconCls: 'icon-cancel',
					onClick: function(){
						win.window("close");
						return false;						
					}
				});
			}
		};
		var source = {
			
			browse : function(perm) {
				var _this = this;
				var datagrid = $("<table></table>");
				var tools = $('<div></div>');
				var addButton = $('<a href="#" class="icon-add"></a>').appendTo(tools);
				addButton.click(function() {
					_this.add(datagrid, perm);
					return false;
				});
				var rmButton = $('<a href="#" class="icon-remove"></a>').appendTo(tools);
				rmButton.click(function() {
					$.messager.confirm("请确认：", "确认要删除所选资源吗？", function(isOk) {
						if(isOk) {
							var items = datagrid.datagrid("getChecked");
							var uris = [];
							$(items).each(function() {
								uris.push(this.uri);
							});
							$.messager.mask().text("操作执行中，请稍后……");
							$.post(me.ctx + "/manager/source/remove", {uris : uris}, function(data) {
								if(data.success) {
									rmButton.hide();
									datagrid.datagrid("reload");
								}
								$.messager.mask('close');
							}, "json");							
						}
					});
					return false;
				});
				var win = me.createWindow('<div></div>', {
					title:"资源管理 - <font color='blue'>所属权限：</font><font style='font-weight:normal;'>" + perm.name + "</font>",
					width:550,
					height:300,
					tools : tools,
					minimizable:false,
					modal:true
				});
				
				datagrid.appendTo(win);
				datagrid.datagrid({
					fit : true,
					url : me.ctx + "/manager/source/browse",
					queryParams : {
						per_id : perm.id
					},
					pagination : true,
					pageSize : 10,
					selectOnCheck : false,
					checkOnSelect : false,
					singleSelect : true,
				    columns : [[
				    	{field : 'checkbox', checkbox : true},
				        {field : 'uri', title : '资源链接', width:200}
				    ]],
				    onClickCell : function(index, field, value) {
				    	if(field === "source") {
				    		var rows = datagrid.datagrid("getRows");
				    		source.browse(rows[index]);
				    	}
				    },
				    onCheckAll : function(rows) {
				    	if(rows.length > 0) {
				    		rmButton.show();
				    	}
				    },
				    onUncheckAll : function(rows) {
				    	rmButton.hide();
				    },
				    onCheck : function(index, row) {
				    	rmButton.show();
				    },
				    onUncheck : function(index, row) {
				    	if($(this).datagrid("getChecked").length < 1) {
				    		rmButton.hide();
				    	}
				    }, 
				    onLoadSuccess : function() {
				    	rmButton.hide();
				    }
				});
				return win;
			},
			
			add:function(datagrid, perm) {
				var _this = this;
				var footer = $('<div style="padding:5px;text-align:right;"></div>');
				var win = me.createWindow('<div></div>', {
					title:"资源添加",
					width:300,
					height:95,
					resizable:false,
					minimizable:false,
					maximizable:false,
					modal:true,
					footer:footer
				});
				var form = $('<form style="width:100%;" method="post"></form>').appendTo(win);
				form.form({
					url : me.ctx + "/manager/source/add",
					success: function(data){
						$.messager.mask("close");
				        var data = eval('(' + data + ')');
				        if (data.success){
				        	datagrid.datagrid("options").pageNumber = 1;
				            datagrid.datagrid("reload");
				            win.window("close");
				        } else {
				        	$.messager.alert('提示：', data.message, "info");
				        }
				    }
				});
				var table = $('<table width="100%" class="form-table"></table>').appendTo($('<div style="padding:5px 5px;"></div>').appendTo(form));
				var row = table.row();
				row.cell("资源URI：", {width:"60px"});
				var fieldContainer = row.cell($('<input type="hidden" name="per_id" value="' + perm.id + '" />'));
				var field = $('<input type="text" name="uri" />').appendTo(fieldContainer);
				field.textbox({
					required: true,
					validType : ['uri', 'maxlength[200]']
				});
				
				var saveButton = $('<a href="#">提交</a>').appendTo(footer);
				saveButton.linkbutton({
					iconCls : 'icon-ok',
					onClick : function() {
						if(form.form("validate")) {
							$.messager.mask().text("操作执行中，请稍后……");
							form.form("submit");
						}
						return false;						
					}
				});
				footer.append("&nbsp;");
				var cancelButton = $('<a href="#">取消</a>').appendTo(footer);
				cancelButton.linkbutton({
					iconCls: 'icon-cancel',
					onClick: function(){
						win.window("close");
						return false;						
					}
				});
			}
		};
		app.browse();
	}
})